import urllib2
import json
from decimal import *

rates = []

def load_rates():
    global rates
    if rates: return
    js = json.loads(urllib2.urlopen("https://raw.github.com/currencybot/open-exchange-rates/master/latest.json").read())
    rates = js["rates"]

def get_rate(code):
    global rates
    load_rates()
    return rates[code.upper()]

def convert(from_code, to_code, amount):
    return float(amount) / get_rate(from_code) * get_rate(to_code)
